package com.alibaba.cloud.apigateway.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * created by wuquan at 05/11/2021
 * ^_^ ^_^
 * 自定义，过滤器
 * MyCustomGatewayFilterFactory
 */
@Slf4j
//@Component
public class MyCustomGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {

    @Override
    public GatewayFilter apply(NameValueConfig config) {

        return new TimeMonitorGatewayFilter(config);
    }


    public static class TimeMonitorGatewayFilter implements GatewayFilter, Ordered{

        private NameValueConfig nameValueConfig;

        public TimeMonitorGatewayFilter(NameValueConfig nameValueConfig) {
            this.nameValueConfig = nameValueConfig;
        }

        /**
         *
         * @param exchange
         * ServerWebExchange是一个HTTP请求-响应交互的契约。提供对HTTP请求和响应的访问，并公开额外的服务器端处理相关属性和特性，如请求属性。
         *
         * 其实，ServerWebExchange命名为服务网络交换器，存放着重要的请求-响应属性、请求实例和响应实例等等，有点像Context的角色
         * @param chain
         * @return
         */
        @Override
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            long start = System.currentTimeMillis();
            MultiValueMap<String, String> queryParams =
                    exchange.getRequest().getQueryParams();
            System.out.println(JSON.toJSONString(queryParams));

            log.info(nameValueConfig.getName());
            /*
            修改请求路径
            ServerHttpRequest request = exchange.getRequest();
            request.mutate().path("/new_path").build();
            return chain.filter(exchange.mutate().request(request).build());*/
            //chain.filter(exchange);




            return chain.filter(exchange).then(Mono.fromRunnable(() ->{

                long s = System.currentTimeMillis() - start;
                System.out.println(s + "ms");
            }));
        }

        @Override
        public int getOrder() {
            return -100;
        }
    }


}
